﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.IO;
using System.Data;

using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.HSSF.UserModel;
using NPOI.HPSF;
using NPOI.POIFS.FileSystem;

namespace SmartExporter
{
    /// <summary>
    /// 日期：2022年3月25日
    /// 类名：Excel帮助类
    /// 说明：进行了简单封装
    /// </summary>
    public class ExcelHelper
    {
        private string fileName = null; //文件名
        private IWorkbook workbook = null;
        private FileStream fs = null;
        private bool disposed;

        public ExcelHelper(string fileName)
        {
            this.fileName = fileName;
            disposed = false;
        }

        /// <summary>
        /// 将DataTable数据导入到excel中
        /// </summary>
        /// <param name="data">要导入的数据</param>
        /// <param name="isColumnWritten">DataTable的列名是否要导入</param>
        /// <param name="sheetName">要导入的excel的sheet的名称</param>
        /// <returns>导入数据行数(包含列名那一行)</returns>
        public int DataTableToExcel(DataTable data, string sheetName, bool isColumnWritten)
        {
            int i = 0;
            int j = 0;
            int count = 0;
            ISheet sheet = null;

            fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
            if (fileName.IndexOf(".xlsx") > 0) // 2007版本
                workbook = new XSSFWorkbook();
            else if (fileName.IndexOf(".xls") > 0) // 2003版本
                workbook = new HSSFWorkbook();

            try
            {
                if (workbook != null)
                {
                    sheet = workbook.CreateSheet(sheetName);
                }
                else
                {
                    return -1;
                }

                if (isColumnWritten == true) //写入DataTable的列名
                {
                    IRow row = sheet.CreateRow(0);
                    for (j = 0; j < data.Columns.Count; ++j)
                    {
                        row.CreateCell(j).SetCellValue(data.Columns[j].ColumnName);
                    }
                    count = 1;
                }
                else
                {
                    count = 0;
                }

                for (i = 0; i < data.Rows.Count; ++i)
                {
                    IRow row = sheet.CreateRow(count);
                    for (j = 0; j < data.Columns.Count; ++j)
                    {
                        row.CreateCell(j).SetCellValue(data.Rows[i][j].ToString());
                    }
                    ++count;
                }
                workbook.Write(fs); //写入到excel
                return count;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception: " + ex.Message);
                return -1;
            }
        }


        /// <summary>
        /// 导出数据到模板Exccel里
        /// </summary>
        /// <param name="excelTemplatePath">模板路径：--模板为.xls类型的Excel</param>
        /// <param name="exportExcelPath">导出路径</param>
        /// <param name="data">严格对应模板展示数据列顺序的DataTable</param>
        /// <param name="sheetName">模板所在的Sheet工作薄</param>
        /// <param name="startRow">除去表头的数据起始行</param>
        /// <returns>是否成功</returns>
        public bool DataTableToTemplateExcel(string excelTemplatePath, string exportExcelPath, DataTable data, string sheetName, int startRow, string strDepartmentName)
        {
            try
            {
                FileStream file = new FileStream(excelTemplatePath, FileMode.Open, FileAccess.Read);
                HSSFWorkbook hssfworkbook = new HSSFWorkbook(file);
                file.Close();
                HSSFSheet ws = (HSSFSheet)hssfworkbook.GetSheet(sheetName);
                hssfworkbook.FirstVisibleTab = 0;//默认显示第一个工作薄Sheet1
                                                 //公共样式：加边框
                NPOI.SS.UserModel.ICellStyle style = hssfworkbook.CreateCellStyle();

                style.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
                style.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
                style.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
                style.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
                style.Alignment = HorizontalAlignment.Center;
                for (int i = 0; i < data.Rows.Count; i++)
                {
                    IRow row = ws.CreateRow(i + startRow);
                    for (int j = 0; j < data.Columns.Count; ++j)
                    {
                        var cell = row.CreateCell(j);
                        row.GetCell(j).SetCellValue(data.Rows[i][j].ToString());

                        cell.CellStyle = style;
                    }
                }
                //处理表头的动车所：
                HSSFCellStyle cs_Title = (HSSFCellStyle)hssfworkbook.CreateCellStyle(); //创建列头样式

                #region 设置单位
                IFont font = hssfworkbook.CreateFont();//创建字体
                font.FontHeightInPoints = 14;
                font.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.Bold;
                font.FontName = "宋体";
                ws.GetRow(1).GetCell(3).CellStyle.SetFont(font);
                ws.GetRow(1).GetCell(3).SetCellValue("南京动车段" + strDepartmentName);
                #endregion

                //保存到导出路径
                ws.ForceFormulaRecalculation = true;
                FileStream files = new FileStream(exportExcelPath, FileMode.Create);
                hssfworkbook.Write(files);
                files.Close();
                return true;
            }
            catch (Exception ec)
            {
                return false;
            }
        }



        public ISheet GetSheet(string sheetName)
        {
            ISheet sheet = null;
            DataTable data = new DataTable();
            int startRow = 0;

            fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
            if (fileName.IndexOf(".xlsx") > 0) // 2007版本
                workbook = new XSSFWorkbook(fs);
            else if (fileName.IndexOf(".xls") > 0) // 2003版本
                workbook = new HSSFWorkbook(fs);

            if (sheetName != null)
            {
                sheet = workbook.GetSheet(sheetName);
                if (sheet == null) //如果没有找到指定的sheetName对应的sheet，则尝试获取第一个sheet
                {
                    sheet = workbook.GetSheetAt(0);
                }
            }
            else
            {
                sheet = workbook.GetSheetAt(0);
            }
            fs.Close();
            return sheet;
        }



        /// <summary>
        /// 将excel中的数据导入到DataTable中
        /// </summary>
        /// <param name="sheetName">excel工作薄sheet的名称</param>
        /// <param name="isFirstRowColumn">第一行是否是DataTable的列名</param>
        /// <returns>返回的DataTable</returns>
        public DataTable ExcelToDataTable(string sheetName, bool isFirstRowColumn)
        {
            ISheet sheet = null;
            DataTable data = new DataTable();
            int startRow = 0;
            try
            {
                sheet = GetSheet(sheetName);
                if (sheet != null)
                {
                    IRow firstRow = sheet.GetRow(0);
                    int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数

                    if (isFirstRowColumn)
                    {
                        for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                        {
                            ICell cell = firstRow.GetCell(i);
                            if (cell != null)
                            {
                                string cellValue = cell.StringCellValue;
                                if (cellValue != null)
                                {
                                    DataColumn column = new DataColumn(cellValue);
                                    data.Columns.Add(column);
                                }
                            }
                        }
                        startRow = sheet.FirstRowNum + 1;
                    }
                    else
                    {
                        startRow = sheet.FirstRowNum;
                    }

                    //最后一列的标号
                    int rowCount = sheet.LastRowNum;
                    for (int i = startRow; i <= rowCount; ++i)
                    {
                        IRow row = sheet.GetRow(i);
                        //修改：yzk 日期：2019-12-10 目的:改为出现空行就截止跳转break不再循环检查下一行
                        if (row == null) break; //没有数据的行默认是null　
                        //if (row == null) continue; //没有数据的行默认是null　　　　　　　

                        DataRow dataRow = data.NewRow();
                        //yzk 2019-12-10 解决获取到行数据不为null，但单元格为空的情况
                        if (row.FirstCellNum == -1) break;
                        for (int j = row.FirstCellNum; j < cellCount; ++j)
                        {
                            //if (row.GetCell(j) != null) //同理，没有数据的单元格都默认是null
                            //{
                            //    if(row.GetCell(j).)
                            //    dataRow[j] = row.GetCell(j).ToString();
                            //}

                            dataRow[j] = GetCellValue(row.GetCell(j));



                        }
                        data.Rows.Add(dataRow);
                    }
                }

                return data;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception: " + ex.Message);
                return null;
            }
        }



        /// <summary>
        /// 将excel中的数据导入到DataTable中
        /// </summary>
        /// <param name="sheetName">excel工作薄sheet的名称</param>
        /// <param name="TitleRowIndex">标题所在行索引，注意起始是0</param>
        /// <returns>返回的DataTable</returns>
        public DataTable ExcelToDataTable(string sheetName, int TitleRowIndex)
        {
            ISheet sheet = null;
            DataTable data = new DataTable();
            int startRow = 0;
            try
            {
                sheet = GetSheet(sheetName);
                if (sheet != null)
                {
                    IRow firstRow = sheet.GetRow(TitleRowIndex);
                    int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数

                    if (TitleRowIndex > 0)
                    {
                        for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                        {
                            ICell cell = firstRow.GetCell(i);
                            if (cell != null)
                            {
                                string cellValue = cell.StringCellValue;
                                if (cellValue != null)
                                {
                                    DataColumn column = new DataColumn(cellValue);
                                    data.Columns.Add(column);
                                }
                            }
                        }
                        startRow = sheet.FirstRowNum + TitleRowIndex + 1;
                    }
                    else
                    {
                        startRow = sheet.FirstRowNum;
                    }

                    //最后一行的标号
                    int rowCount = sheet.LastRowNum;
                    for (int i = startRow; i <= rowCount; ++i)
                    {
                        IRow row = sheet.GetRow(i);
                        //修改：yzk 日期：2019-12-10 目的:改为出现空行就截止跳转break不再循环检查下一行
                        if (row == null) break; //没有数据的行默认是null　　　　　　　
                        //if (row == null) continue; //没有数据的行默认是null　(旧的写法)
                        DataRow dataRow = data.NewRow();
                        //yzk 2019-12-10 解决获取到行数据不为null，但单元格为空的情况
                        if (row.FirstCellNum == -1) break;
                        for (int j = row.FirstCellNum; j < cellCount; ++j)
                        {
                            dataRow[j] = GetCellValue(row.GetCell(j));
                        }
                        data.Rows.Add(dataRow);
                    }
                }

                return data;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception: " + ex.Message);
                return null;
            }
        }

        /// <summary>
        /// 将excel中的数据导入到DataTable中,去掉无效的行，无效的列（通过行列为空进行判断）no invalid rows or columns
        /// </summary>
        /// <param name="sheetName">excel工作薄sheet的名称</param>
        /// <param name="TitleRowIndex">标题所在行索引，注意起始是0</param>
        /// <returns>返回的DataTable</returns>
        public DataTable ExcelToDataTableNoInvalidRowsColumns(string sheetName, int TitleRowIndex)
        {
            ISheet sheet = null;
            DataTable data = new DataTable();
            int startRow = 0;
            try
            {
                sheet = GetSheet(sheetName);
                if (sheet != null)
                {
                    IRow firstRow = sheet.GetRow(TitleRowIndex);

                    int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数

                    if (TitleRowIndex > 0)
                    {
                        for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                        {
                            ICell cell = firstRow.GetCell(i);
                            if (cell != null)
                            {
                                string cellValue = cell.StringCellValue;
                                if (!string.IsNullOrEmpty(cellValue))
                                {
                                    DataColumn column = new DataColumn(cellValue);
                                    data.Columns.Add(column);
                                }
                                else//列名为空说明为最后一列
                                {
                                    cellCount = i;//最后一列的cell编号，即总的列数
                                    break;
                                }
                            }
                        }
                        startRow = sheet.FirstRowNum + TitleRowIndex + 1;
                    }
                    else
                    {
                        startRow = sheet.FirstRowNum;
                    }

                    //最后一行的标号
                    int rowCount = sheet.LastRowNum;
                    for (int i = startRow; i <= rowCount; ++i)
                    {
                        IRow row = sheet.GetRow(i);
                        if (row == null) break; //没有数据的行直接退出说明到行尾了

                        DataRow dataRow = data.NewRow();
                        if (row.FirstCellNum == -1) break;
                        for (int j = row.FirstCellNum; j < cellCount; ++j)
                        {
                            ICell cell = row.GetCell(0);
                            if (cell != null)
                            {
                                //每一行的第一列如果为空则直接退出来，说明到最后一行了
                                if (string.IsNullOrEmpty(GetCellValue(cell).ToString()))
                                {
                                    break;
                                }
                            }
                            else
                            {
                                break;
                            }
                            dataRow[j] = GetCellValue(row.GetCell(j));
                        }
                        data.Rows.Add(dataRow);
                    }
                }

                return data;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception: " + ex.Message);
                return null;
            }
        }


        public static object GetCellValue(ICell cell)
        {
            // ICell cell = row.GetCell(j);
            if (cell == null)
                return null;

            switch (cell.CellType)
            {

                case NPOI.SS.UserModel.CellType.Blank: //BLANK:  
                    return null;
                case NPOI.SS.UserModel.CellType.Boolean: //BOOLEAN:  
                    return cell.BooleanCellValue;
                case NPOI.SS.UserModel.CellType.Numeric: //NUMERIC:  
                    short format = cell.CellStyle.DataFormat;
                    if (format != 0) { return cell.DateCellValue; } else { return cell.NumericCellValue; }
                case NPOI.SS.UserModel.CellType.String: //STRING:  
                    return cell.StringCellValue;
                case NPOI.SS.UserModel.CellType.Error: //ERROR:  
                    return cell.ErrorCellValue;
                case NPOI.SS.UserModel.CellType.Formula: //FORMULA:  
                default:
                    return "=" + cell.CellFormula;
            }
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    if (fs != null)
                        fs.Close();
                }

                fs = null;
                disposed = true;
            }
        }

        /// <summary>
        /// 作者：YangZhike
        /// 创建日期：2019-8-29
        /// 描述：将数据导入到指定路径下的文件里
        /// </summary>
        /// <param name="excelTemplatePath"></param>
        /// <param name="exportExcelPath"></param>
        /// <param name="data"></param>
        /// <param name="sheetName"></param>
        /// <param name="startRow"></param>
        /// <param name="strDepartmentName"></param>
        /// <returns></returns>
        public bool DataTableToPathExcel(string excelTemplatePath, string exportExcelPath, DataTable data, string sheetName)
        {
            try
            {
                FileStream file = new FileStream(excelTemplatePath, FileMode.Open, FileAccess.Read);
                HSSFWorkbook hssfworkbook = new HSSFWorkbook(file);
                file.Close();
                HSSFSheet ws = (HSSFSheet)hssfworkbook.GetSheet(sheetName);
                hssfworkbook.FirstVisibleTab = 0;//默认显示第一个工作薄Sheet1
                //处理列头
                IRow rowFirst = ws.CreateRow(0);
                for (int i = 0; i < data.Columns.Count; i++)
                {
                    rowFirst.CreateCell(i);
                    rowFirst.GetCell(i).SetCellValue(data.Columns[i].ColumnName);
                }
                //处理行数据
                for (int i = 0; i < data.Rows.Count; i++)
                {
                    IRow row = ws.CreateRow(i + 1);
                    for (int j = 0; j < data.Columns.Count; ++j)
                    {
                        row.CreateCell(j);
                        row.GetCell(j).SetCellValue(data.Rows[i][j].ToString());
                    }
                }
                //保存到导出路径
                ws.ForceFormulaRecalculation = true;
                FileStream files = new FileStream(exportExcelPath, FileMode.Create);
                hssfworkbook.Write(files);
                files.Close();
                return true;
            }
            catch (Exception ec)
            {
                return false;
            }
        }

    }
}
